import { ref, reactive } from 'vue';
import { ElMessage, dayjs } from 'element-plus';
import demandApi from '@/apis/demand';

/**
 * 需求管理相关的Hook
 */
export function useDemandManagement() {
  // 状态管理
  const loading = ref(false);
  const demandData = ref([]);
  
  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });
  
  // 搜索条件
  const searchParams = reactive({
    title: '',
    status: '',
    userId: '',
    enterpriseId: ''
  });

  /**
 * 获取需求列表数据
 */
  const fetchDemandData = async () => {
    loading.value = true;
    
    try {
      const params = {
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
        title: searchParams.title,
        status: searchParams.status !== '' ? parseInt(searchParams.status) : null
      };
      
      // 调用真实API获取需求列表
      const response = await demandApi.getDemandList(params);
      
      // 处理后端返回的数据，后端返回格式为 {code: 200, message: 'success', data: {records: [...], total: 100}}  
      if (response.data && response.code === 200) {
        console.log('response.data:', response.data);
        
        // 确保resultData是对象格式
        const resultData = response.data || {};
        console.log('resultData:', resultData);
        // 将后端数据格式化为前端所需格式，确保变量名匹配
        // 安全地处理records数组
        demandData.value = (resultData.records || []).map(item => ({
          id: item.id,
          userId: item.userId,
          userName: item.userName || '',
          title: item.title,
          description: String(item.description || '').trim(), // 确保描述字段正确处理
          budget: item.budget,
          deadline: item.deadline ? dayjs(item.deadline).format('YYYY-MM-DD') : '',
          status: item.status?.toString() || '0', // 确保状态为字符串格式
          statusText: item.statusText || '',
          publishTime: item.publishTime ? dayjs(item.publishTime).format('YYYY-MM-DD HH:mm:ss') : '',
          auditRemark: String(item.auditRemark || '').trim() // 确保审核备注字段正确处理
        }));
        
        // 更新分页信息
        pagination.currentPage = resultData.current || pagination.currentPage;
        pagination.pageSize = resultData.size || pagination.pageSize;
        pagination.total = resultData.total || 0;
      } else {
        throw new Error(response.data?.message || '获取数据失败');
      }
    } catch (error) {
      ElMessage.error('获取需求数据失败: ' + (error.message || ''));
      console.error('获取需求数据错误:', error);
      demandData.value = [];
      pagination.total = 0;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 搜索需求
   */
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchDemandData();
  };

  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    Object.assign(searchParams, {
      title: '',
      status: '',
      userId: '',
      enterpriseId: ''
    });
    pagination.currentPage = 1;
    fetchDemandData();
  };

  /**
   * 分页大小变化
   */
  const handleSizeChange = (size) => {
    pagination.pageSize = size;
    fetchDemandData();
  };

  /**
   * 页码变化
   */
  const handleCurrentChange = (current) => {
    pagination.currentPage = current;
    fetchDemandData();
  };

  // 添加需求
  const addDemand = async (demandData) => {
    try {
      const response = await demandApi.addDemand(demandData);
      
      if (response.data && response.code === 200) {
        ElMessage.success('添加需求成功');
        fetchDemandData(); // 重新获取需求列表
        return true;
      } else {
        throw new Error(response.data?.message || '添加需求失败');
      }
    } catch (error) {
      ElMessage.error('添加需求失败: ' + (error.message || ''));
      console.error('添加需求错误:', error);
      return false;
    }
  };
  
  // 更新需求
  const updateDemand = async (id, demandData) => {
    try {
      const response = await demandApi.updateDemand(id, demandData);
      
      if (response.data && response.code === 200) {
        ElMessage.success('更新需求成功');
        fetchDemandData(); // 重新获取需求列表
        return true;
      } else {
        throw new Error(response.data?.message || '更新需求失败');
      }
    } catch (error) {
      ElMessage.error('更新需求失败: ' + (error.message || ''));
      console.error('更新需求错误:', error);
      return false;
    }
  };
  
  // 删除需求
  const deleteDemand = async (id) => {
    try {
      const response = await demandApi.deleteDemand(id);
      
      if (response.data && response.code === 200) {
        ElMessage.success('删除需求成功');
        fetchDemandData(); // 重新获取需求列表
        return true;
      } else {
        throw new Error(response.data?.message || '删除需求失败');
      }
    } catch (error) {
      ElMessage.error('删除需求失败: ' + (error.message || ''));
      console.error('删除需求错误:', error);
      return false;
    }
  };
  
  // 审核需求
  const auditDemand = async (auditData) => {
    try {
      console.log('auditData:', auditData);
      const response = await demandApi.auditDemand(auditData);
      
      if (response.data && response.code === 200) {
        ElMessage.success('审核需求成功');
        fetchDemandData(); // 重新获取需求列表
        return true;
      } else {
        throw new Error(response.data?.message || '审核需求失败');
      }
    } catch (error) {
      ElMessage.error('审核需求失败: ' + (error.message || ''));
      console.error('审核需求错误:', error);
      return false;
    }
  };

  /**
   * 获取需求状态文本
   */
  const getStatusText = (status) => {
    const statusMap = {
      '0': '待审核',
      '1': '审核通过',
      '2': '审核拒绝',
      '3': '已发布',
      '4': '已接单',
      '5': '进行中',
      '6': '已完成',
      '7': '已关闭'
    };
    return statusMap[status] || '未知状态';
  };

  /**
   * 获取需求状态标签类型
   */
  const getStatusTagType = (status) => {
    const typeMap = {
      '0': 'warning',
      '1': 'primary',
      '2': 'danger',
      '3': 'success',
      '4': 'info',
      '5': 'processing',
      '6': 'success',
      '7': 'default'
    };
    return typeMap[status] || 'default';
  };

  return {
    loading,
    demandData,
    pagination,
    searchParams,
    fetchDemandData,
    handleSearch,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
    addDemand,
    updateDemand,
    deleteDemand,
    auditDemand,
    getStatusText,
    getStatusTagType
  };
}

// 添加默认导出，兼容不同的导入方式
export default useDemandManagement;